package com.siyoumi.app.service;

import com.siyoumi.app.entity.SysItem;
import com.siyoumi.app.entity.SysItemData;
import com.siyoumi.app.mapper.SysItemMapper;
import com.siyoumi.app.modules.app_admin.vo.SysItemVo;
import com.siyoumi.app.sys.vo.CommonItemData;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.service.ServiceImplBase;
import com.siyoumi.component.XSpringContext;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


//t_sys_item
@Service
public class SysItemService
        extends ServiceImplBase<SysItemMapper, SysItem> {
    static public SysItemService getBean() {
        return XSpringContext.getBean(SysItemService.class);
    }

    public List<SysItem> listByAppId(String appId) {
        JoinWrapperPlus<SysItem> query = join();
        query.eq("item_app_id", appId)
                .eq("item_x_id", "");
        return list(query);
    }

    public SysItem getEntityByIdSrc(String idSrc, String x) {
        JoinWrapperPlus<SysItem> query = join();
        query.eq("item_x_id", x)
                .eq("item_id_src", idSrc);
        return first(query);
    }

    public SysItem getEntityByIdSrc(String idSrc) {
        return getEntityByIdSrc(idSrc, XHttpContext.getX());
    }

    public List<CommonItemData> getItemDataByIdSrc(String idSrc) {
        SysItem entityItem = getEntityByIdSrc(idSrc);
        if (entityItem == null) {
            return new ArrayList<>();
        }

        return entityItem.commonData();
    }


    /**
     * 根据模板，获取值
     *
     * @param itemId 模板属性ID
     * @param key    key，如：活动ID
     */
    public Map<String, String> getItemData(String itemId, String key) {
        SysItemData entityData = SysItemDataService.getBean().getEntityByKey(itemId, key);
        Map<String, String> mapData = new HashMap<>();
        if (entityData != null) {
            mapData = entityData.data();
        }

        SysItem entityItem = getEntity(itemId);
        List<SysItemVo> listItem = entityItem.commonData(SysItemVo.class);

        Map<String, String> mapVal = new HashMap<>();
        for (SysItemVo itemData : listItem) {
            String val = itemData.getDef();
            if (mapData.containsKey(itemData.getField_key())) {
                val = mapData.get(itemData.getField_key());
            }

            mapVal.put(itemData.getField_key(), val);
        }

        return mapVal;
    }
}
